package com.fjnu.dao.impl;

import com.fjnu.dao.CommentDao;
import com.fjnu.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class CommentDaoImpl implements CommentDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    public int insert(Comment newComment) {
        String sql = "INSERT INTO tb_comment (content,article_id,user_id,support,oppose,create_time,update_time) VALUES (?,?,?,?,?,?,?)";
        int result = jdbcTemplate.update(sql,
                newComment.getContent(),
                newComment.getArticleId(),
                newComment.getUserId(),
                newComment.getSupport(),
                newComment.getOppose(),
                newComment.getCreateTime(),
                newComment.getUpdateTime()
                );
        return result > 0 ? 1 : 0;
    }

    @Override
    public int updateSupport(Integer commentId, Integer incremented) {
        String sql = "UPDATE tb_comment SET support = support + ? WHERE id = ?";
        int result = jdbcTemplate.update(sql, incremented, commentId);
        return result > 0 ? 1 : 0;
    }

    @Override
    public int updateOppose(Integer commentId, Integer incremented) {
        String sql = "UPDATE tb_comment SET oppose = oppose + ? WHERE id = ?";
        int result = jdbcTemplate.update(sql, incremented, commentId);
        return result > 0 ? 1 : 0;
    }

    @Override
    public List<Comment> selectAllCommentsForArticle(Integer articleId) {
        String sql = "SELECT * FROM tb_comment WHERE article_id = ? ORDER BY create_time DESC";
        return jdbcTemplate.query(sql, new CommentRowMapper(), articleId);
    }

    @Override
    public List<Comment> selectCommentsWithLimitForArticle(Integer articleId, Integer startIndex, Integer endIndex) {
        String sql = "SELECT * FROM tb_comment WHERE article_id = ? ORDER BY create_time DESC LIMIT ?, ?";
        return jdbcTemplate.query(sql, new CommentRowMapper(), articleId, startIndex, endIndex);
    }
    private static class CommentRowMapper implements org.springframework.jdbc.core.RowMapper<Comment> {
        @Override
        public Comment mapRow(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException {
            Comment comment = new Comment();
            comment.setId(rs.getInt("id"));
            comment.setContent(rs.getString("content"));
            comment.setArticleId(rs.getInt("article_id"));
            comment.setUserId(rs.getInt("user_id"));
            comment.setSupport(rs.getInt("support"));
            comment.setOppose(rs.getInt("oppose"));
            comment.setCreateTime(rs.getTimestamp("create_time"));
            comment.setUpdateTime(rs.getTimestamp("update_time"));
            return comment;
        }
    }
}
